<?php

/*
 *  usage of $preserve_aspect_ratio
 * 
 *     false : strech
 *     height : use supplied height and calculate width from image's aspect ratio
 *     width : use supplied width and calculate height from image's aspect ratio
 * 
 *  by Adel Abu-Saif :D
 */

function get_resized_image($width, $height, $local_path, $preserve_aspect_ratio = false, $crop = true) {

    if(!is_file($local_path)) return false;
    
    $original_image_size = getimagesize($local_path);

    $basename = basename($local_path);
    $new_name = $width . 'x' . $height . '_' . $basename;
    $path_only = str_replace($basename, '', $local_path);
    $path_only .= 'thumbs/';

    if (!is_dir($path_only)) {
        mkdir($path_only);
        chmod($path_only, 777);
    }

    $new_local_path = $path_only . $new_name;

    if ($width == $original_image_size[0] && $height == $original_image_size[1]) {
        $path_only = str_replace($basename, '', $local_path);
        $new_public_path = str_replace(sfConfig::get('sf_web_dir'), public_path('/', true), $path_only . $basename);
        return $new_public_path;
    }

    if ($preserve_aspect_ratio) {
        $original_width = $original_image_size[0];
        $original_height = $original_image_size[1];
    }

    
    switch ($preserve_aspect_ratio) {
        case 'height':
            $width = floor(($height * $original_width) / $original_height);
            $new_name = $width . 'x' . $height . '_' . $basename;
            $new_local_path = $path_only . $new_name;
            break;
        case 'width':
            $height = floor(($width * $original_height) / $original_width);
            $new_name = $width . 'x' . $height . '_' . $basename;
            $new_local_path = $path_only . $new_name;
            break;
    }

    if (!file_exists($new_local_path)) {
        $image = new SimpleImage();
        $image->load($local_path);

        $image->resize($width, $height, $crop);

        $image->save($new_local_path);
    }

    $new_public_path = str_replace(sfConfig::get('sf_web_dir'), public_path('/', true), $new_local_path);
    
    $new_public_path = str_replace('/\\', '/', $new_public_path);
    
    return $new_public_path;
}